package me.xpyex.plugin.fixprimordialpearl;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.PrepareAnvilEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;

public class HandleEvent implements Listener {
    public static boolean isPrimordialPearl(String type) {
        type = type.toLowerCase();
        //不同Forge+Bukkit核心向Bukkit注册物品枚举的方式不同，不可以直接equals
        return type.startsWith("thaumcraft") && type.endsWith("primordial_pearl");
    }

    @EventHandler
    public void onAnvilChange(PrepareAnvilEvent event) {
        if (event == null) {  //莫名其妙，有的情况下event为空，我都不知道怎么触发的
            return;
        }

        if (event.getInventory().getItem(1) == null || event.getInventory().getItem(1).getType() == Material.AIR) {
            return;
        }
        String rightSlotType = event.getInventory().getItem(1).getType().toString().toLowerCase();

        if (isPrimordialPearl(rightSlotType)) {
            event.setResult(new ItemStack(Material.AIR));
            FixPrimordialPearl.LOGGER.info("玩家 " + event.getView().getPlayer().getName() + " 尝试使用元始珍珠Bug，已尝试拦截. 具体坐标: " + event.getView().getPlayer().getLocation().toString());
        }
    }

    @EventHandler
    public void onInvClick(InventoryClickEvent event) {
        if (!(event.getWhoClicked() instanceof Player && FixPrimordialPearl.PLAYERS_CHECKING.containsKey(event.getWhoClicked().getUniqueId()))) {
            return;
        }
        //玩家已在铁砧界面
        if (event.getClickedInventory() != event.getWhoClicked().getInventory()) {  //点击“铁砧”
            if (event.getClick() == ClickType.NUMBER_KEY && (event.getSlot() == 0 || event.getSlot() == 1)) {  //快捷键操作
                event.getWhoClicked().getServer().getScheduler().runTaskLater(FixPrimordialPearl.INSTANCE, () -> {
                    ItemStack item = event.getCurrentItem();
                    if (item == null) return;
                    if (isPrimordialPearl(item.getType().toString())) {
                        event.getWhoClicked().sendMessage(FixPrimordialPearl.PLAYERS_CHECKING.get(event.getWhoClicked().getUniqueId()));
                        event.getWhoClicked().closeInventory();
                        FixPrimordialPearl.PLAYERS_CHECKING.remove(event.getWhoClicked().getUniqueId());
                        FixPrimordialPearl.LOGGER.info("玩家 " + event.getWhoClicked().getName() + " 尝试使用元始珍珠Bug，已尝试拦截. 具体坐标: " + event.getWhoClicked().getLocation().toString());
                        Bukkit.getScheduler().runTask(FixPrimordialPearl.INSTANCE, () -> ((Player) event.getWhoClicked()).updateInventory());
                    }
                }, 1L);
            }
        } else {  //点击自身背包
            if (event.getCurrentItem() == null) return;
            if (isPrimordialPearl(event.getCurrentItem().getType().toString())) {
                event.getWhoClicked().sendMessage(FixPrimordialPearl.PLAYERS_CHECKING.get(event.getWhoClicked().getUniqueId()));
                event.setCancelled(true);
                event.setResult(Event.Result.DENY);
                event.getWhoClicked().closeInventory();
                FixPrimordialPearl.PLAYERS_CHECKING.remove(event.getWhoClicked().getUniqueId());
                FixPrimordialPearl.LOGGER.info("玩家 " + event.getWhoClicked().getName() + " 尝试使用元始珍珠Bug，已尝试拦截. 具体坐标: " + event.getWhoClicked().getLocation().toString());
                Bukkit.getScheduler().runTask(FixPrimordialPearl.INSTANCE, () -> ((Player) event.getWhoClicked()).updateInventory());
            }
        }
    }

    @EventHandler
    public void onPlayerRightClick(PlayerInteractEvent event) {
        if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
            String clickedBlockType = event.getClickedBlock().getType().toString().toUpperCase();
            //不同Forge+Bukkit核心向Bukkit注册物品枚举的方式不同，不可以直接equals
            if (clickedBlockType.contains("ANVIL") && (!(clickedBlockType.startsWith("ThaumAdditions".toUpperCase()) && clickedBlockType.endsWith("VOID_ANVIL")))) {  //神秘领域中虚空铁砧可触发PrepareAnvilEvent，无需用此方式处理
                if (event.getClickedBlock().getType() == Material.ANVIL) {
                    return;
                }
                Bukkit.getScheduler().runTask(FixPrimordialPearl.INSTANCE, () -> {  //放到下一个tick执行
                    if (event.getPlayer().getOpenInventory().getType().toString().equalsIgnoreCase("Chest")) {
                        FixPrimordialPearl.PLAYERS_CHECKING.put(event.getPlayer().getUniqueId(), "无法在铁砧中使用该物品");
                    }
                });
            }
        }
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        FixPrimordialPearl.PLAYERS_CHECKING.remove(event.getPlayer().getUniqueId());
        //
    }

    @EventHandler
    public void onInvClose(InventoryCloseEvent event) {
        if (event.getPlayer() instanceof Player) {
            FixPrimordialPearl.PLAYERS_CHECKING.remove(event.getPlayer().getUniqueId());
        }
    }
}
